/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package feuerwehr;

import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.List;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

/**
 *
 * @author GundlaPe
 */
public class EinsatzTabelle extends javax.swing.JFrame {

    /**
     * Creates new form EinsatzTabelle
     */
    public EinsatzTabelle() {
        initComponents();
        setTitle(Feuerwehr.STR_VERSION + " *** Übersicht *** ");
        setLocation(100, 100);
        setDefaultWhere("heute", false);
        jtEinsatz.getSelectionModel().addListSelectionListener(lsl);
        jtEinsatz.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        JTableHeader jTableHeader=jtEinsatz.getTableHeader(); 
        jTableHeader.addMouseListener(mouseAdapter);
    }

    public void setAnzeigeEinsatz(AnzeigeEinsatz anzeigeEinsatz) {
        this.anzeigeEinsatz = anzeigeEinsatz;
    }
    
    public void refreshAnzeige() {
        rebuild=true;

        einsatzDatenList = EinsatzDaten.readData(defaultWhere);
        einsatzTableModel = new EinsatzTableModel(einsatzDatenList);
        jtEinsatz.setModel(einsatzTableModel);
        einsatzTableModel.fireTableDataChanged();

        markers = EinsatzDaten.readDataKarte(defaultWhere);
        EinsatzDaten einsatzDaten = einsatzTableModel.getEinsatzDaten(jtEinsatz.getSelectedRow()==-1?0:jtEinsatz.getSelectedRow());
        if (einsatzDaten != null)
            Kartendienst.kartenDienstAlle(jlKarte, einsatzDaten.getData(8), einsatzDaten.getData(9), markers, zoom);
        
        TableColumn column = null;
        for (int i = 0; i < 8; i++) {
            column = jtEinsatz.getColumnModel().getColumn(i);
            switch (i) {
                case 0:     column.setPreferredWidth(80);       // Einsatz-Nr.
                            break;
                case 1:     column.setPreferredWidth(60);       // Beginn
                            break;
                case 2:     column.setPreferredWidth(60);       // Ende
                            break;
                case 3:     column.setPreferredWidth(100);      // Strasse
                            break;
                case 4:     column.setPreferredWidth(6);        // PLZ
                            break;
                case 5:     column.setPreferredWidth(60);       // Ort
                            break;
                case 6:     column.setPreferredWidth(200);      // Fahrzeuge
                            break;
                case 7:     column.setPreferredWidth(100);      // Stichwort
                            break;
            }
        }        

        jtEinsatz.invalidate();
        rebuild=false;
    }
    
    /**
     * Zurückgegen der JCheckBox ob automatisch aktualisiert werden soll.
     * @return true/false
     */
    public boolean getAktualiserung() {
        return jcbAktualisieren.isSelected();
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jbAlle = new javax.swing.JButton();
        jbGestern = new javax.swing.JButton();
        jbHeute = new javax.swing.JButton();
        jbOffene = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtEinsatz = new javax.swing.JTable(einsatzTableModel);
        jpKarte = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jlKarte = new javax.swing.JLabel();
        jbMinus = new javax.swing.JButton();
        jbPlus = new javax.swing.JButton();
        jcbAktualisieren = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jbAlle.setText("Alle");
        jbAlle.setPreferredSize(new java.awt.Dimension(110, 23));
        jbAlle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAlleActionPerformed(evt);
            }
        });

        jbGestern.setText("Gestern/Heute");
        jbGestern.setPreferredSize(new java.awt.Dimension(110, 23));
        jbGestern.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbGesternActionPerformed(evt);
            }
        });

        jbHeute.setText("Heute");
        jbHeute.setPreferredSize(new java.awt.Dimension(110, 23));
        jbHeute.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbHeuteActionPerformed(evt);
            }
        });

        jbOffene.setText("Offene");
        jbOffene.setPreferredSize(new java.awt.Dimension(110, 23));
        jbOffene.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbOffeneActionPerformed(evt);
            }
        });

        jtEinsatz.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"Bitte Auswahl treffen"},
            },
            new String [] {
                "Bitte Auswahl treffen"
            }
        ));
        jScrollPane2.setViewportView(jtEinsatz);

        jpKarte.setLayout(new java.awt.BorderLayout());

        jlKarte.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jScrollPane1.setViewportView(jlKarte);

        jpKarte.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jbMinus.setText("-");
        jbMinus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbMinusActionPerformed(evt);
            }
        });

        jbPlus.setText("+");
        jbPlus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbPlusActionPerformed(evt);
            }
        });

        jcbAktualisieren.setSelected(true);
        jcbAktualisieren.setText("Automatische Aktualisierung");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jbAlle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbGestern, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbHeute, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbOffene, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(118, 118, 118)
                        .addComponent(jbMinus)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbPlus)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 366, Short.MAX_VALUE)
                        .addComponent(jcbAktualisieren, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jpKarte, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbAlle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbGestern, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbHeute, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbOffene, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbMinus)
                    .addComponent(jbPlus)
                    .addComponent(jcbAktualisieren))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jpKarte, javax.swing.GroupLayout.DEFAULT_SIZE, 570, Short.MAX_VALUE)
                .addContainerGap())
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbAlleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAlleActionPerformed
        setDefaultWhere("alle", true);
    }//GEN-LAST:event_jbAlleActionPerformed

    private void jbGesternActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbGesternActionPerformed
        setDefaultWhere("gestern", true);
    }//GEN-LAST:event_jbGesternActionPerformed

    private void jbHeuteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbHeuteActionPerformed
        setDefaultWhere("heute", true);
    }//GEN-LAST:event_jbHeuteActionPerformed

    private void jbOffeneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbOffeneActionPerformed
        setDefaultWhere("offene", true);
    }//GEN-LAST:event_jbOffeneActionPerformed

    private void jbMinusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbMinusActionPerformed
        zoom = String.valueOf(Integer.parseInt(zoom) - 1);
        EinsatzDaten ed1 = einsatzTableModel.getEinsatzDaten(jtEinsatz.getSelectedRow()==-1?0:jtEinsatz.getSelectedRow());
        Kartendienst.kartenDienstAlle(jlKarte, ed1.getData(8), ed1.getData(9), markers, zoom);
    }//GEN-LAST:event_jbMinusActionPerformed

    private void jbPlusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbPlusActionPerformed
        zoom = String.valueOf(Integer.parseInt(zoom) + 1);
        EinsatzDaten ed1 = einsatzTableModel.getEinsatzDaten(jtEinsatz.getSelectedRow()==-1?0:jtEinsatz.getSelectedRow());
        Kartendienst.kartenDienstAlle(jlKarte, ed1.getData(8), ed1.getData(9), markers, zoom);        
    }//GEN-LAST:event_jbPlusActionPerformed

    /**
     * Hier wird das "default where" der Query gesetzt, je nach Button.
     * Anschliessend wird der selektierte Satz als Mittelpunkt der Karte gesetzt.
     * @param button Der übergebene String zur Auswahl
     */
    private void setDefaultWhere(String button, boolean refresh) {
        switch (button) {
            case "alle":    defaultWhere = "1 = 1";
                            break;
            case "gestern": defaultWhere = "date(beginn) >= date(sysdate())-1";
                            break;
            case "heute":   defaultWhere = "date(beginn) = date(sysdate())";
                            break;
            case "offene":   defaultWhere = "ende is null";
                            break;
        }
        if (refresh) {
            refreshAnzeige();
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EinsatzTabelle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EinsatzTabelle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EinsatzTabelle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EinsatzTabelle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new EinsatzTabelle().setVisible(true);
            }
        });
    }
    
    /**
     * ListSelectionListener für JTable, damit auf Klicks reagiert werden kann.
     * Wenn ein Einsatz ausgewählt wird, wird dieser im AnzeigeEinsatz aktualisiert.
     */
    ListSelectionListener lsl= new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent ev) {
            if (rebuild==true) {
                return;
            }
            boolean isAdjusting = ev.getValueIsAdjusting();         // Man bekommt immer zwei Nachrichten(!)
            if (isAdjusting==false) {
                int i = jtEinsatz.getSelectedRow();
                EinsatzDaten ed = einsatzTableModel.getEinsatzDaten(i);
                if (anzeigeEinsatz != null) {
                    anzeigeEinsatz.updateAnzeigeEinsatz(Integer.parseInt(ed.getPK()));
                }
                Kartendienst.kartenDienstAlle(jlKarte, ed.getData(8), ed.getData(9), markers, zoom);
            }
        } 
     };
    
    /**
     * MouseAdapter für JTable um auf Klicks im Header zu reagieren.
     */
    MouseAdapter mouseAdapter = new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            TableColumnModel columnModel = jtEinsatz.getColumnModel();
            int viewColumn = columnModel.getColumnIndexAtX(e.getX());
            int column = jtEinsatz.convertColumnIndexToModel(viewColumn);
            if (e.getClickCount() == 1 && column != -1) {
                int shiftPressed = e.getModifiers() & InputEvent.CTRL_MASK;
                boolean ascending = (shiftPressed == 0);
		EinsatzDaten.setSortColumn(column);
		Collections.sort(einsatzDatenList);
		if (!ascending) {
			Collections.reverse(einsatzDatenList);
		}
		einsatzTableModel.fireTableDataChanged();
		// getSelectionModel().setSelectionInterval(0, 0);                
            }
        }    
    };

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jbAlle;
    private javax.swing.JButton jbGestern;
    private javax.swing.JButton jbHeute;
    private javax.swing.JButton jbMinus;
    private javax.swing.JButton jbOffene;
    private javax.swing.JButton jbPlus;
    private javax.swing.JCheckBox jcbAktualisieren;
    private javax.swing.JLabel jlKarte;
    private javax.swing.JPanel jpKarte;
    private javax.swing.JTable jtEinsatz;
    // End of variables declaration//GEN-END:variables

    private EinsatzTableModel einsatzTableModel;
    private List<EinsatzDaten> einsatzDatenList;
    private AnzeigeEinsatz anzeigeEinsatz;
    private boolean rebuild = false;
    private String defaultWhere = "1 = 1";
    private String markers = "";
    private String zoom = "17";
}
